package com.bp.hearthealth.pulse.lnapps.ads.admob.banner_ad

import android.content.Context
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.view.isGone
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsCount
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.LoadAdError


class AdMobBannerAdManager(
    private val context: Context,
    lifecycleOwner: LifecycleOwner,
    private val adUnitId: String,
    private val bannerAdContainer: ViewGroup,
    private val adListener: AdMobBannerAdListener? = null
) : DefaultLifecycleObserver {
    private var numberRetries = 0
    private lateinit var adView: AdView
    private var isLoaded = false

    init {
        lifecycleOwner.lifecycle.addObserver(this)
        adView = AdView(context)
        bannerAdContainer.addView(adView)
        adView.adUnitId = adUnitId
        adView.setAdSize(adSize)
    }

    override fun onResume(owner: LifecycleOwner) {
        adView.resume()
    }

    override fun onPause(owner: LifecycleOwner) {
        adView.pause()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        adView.destroy()
        owner.lifecycle.removeObserver(this)
    }


    fun loadBannerAd() {
        isLoaded = false
        if (!AdsSwitch.getBoolean(AdsSwitch.adBannerControl)) {
            return
        }
        val adRequest = AdRequest.Builder().build()
        adView.loadAd(adRequest)
        adView.adListener = object : AdListener() {
            override fun onAdClicked() {
                AdsCount.incrementClickCount()
                LogUtil.i("用户点击了Banner广告")
                adListener?.onAdClicked()
            }

            override fun onAdClosed() {
                LogUtil.i("用户关闭了Banner广告")
                adListener?.onAdClosed()
            }

            override fun onAdFailedToLoad(adError: LoadAdError) {
                LogUtil.i("Banner广告请求失败：$adError")
                if (numberRetries < 3) {
                    loadBannerAd()
                }
                numberRetries++
                adListener?.onAdFailedToLoad()
            }

            override fun onAdImpression() {
//                LogUtil.i("Banner广告记录了印象")
                adListener?.onAdImpression()
            }

            override fun onAdLoaded() {
                isLoaded = true
                if (bannerAdContainer.isGone && AdsSwitch.getBoolean(AdsSwitch.adAppControl)) {
                    bannerAdContainer.visibility = View.VISIBLE
                }
                adListener?.onAdLoaded(adView)
            }

            override fun onAdOpened() {
                LogUtil.i("Banner广告打开")
                adListener?.onAdOpened()
            }
        }
    }

    private val adSize: AdSize
        get() {
            val display =
                (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
            val outMetrics = DisplayMetrics()
            display.getMetrics(outMetrics)

            val density = outMetrics.density

            var adWidthPixels = bannerAdContainer.width.toFloat()
            if (adWidthPixels == 0f) {
                adWidthPixels = outMetrics.widthPixels.toFloat()
            }

            val adWidth = (adWidthPixels / density).toInt()
            return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(context, adWidth)
        }
}

